<template>
  <div class="task-material-list">
    <el-button
      class="mb-12"
      @click="openApplyDialog"
      type="primary"
      size="mini"
      plain
    >{{$t('common.base.addModule', {module: ''})}}</el-button>

    <el-table
      header-row-class-name="base-table-header-v3"
      class="task-material-table"
      :row-class-name="getRowClass"
      border
      v-loading="loading"
      :data="data"
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!loading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>

      <!-- start 展开行 -->
      <el-table-column type="expand" width="40" v-if="showExpand">
        <template slot-scope="scope">
          <task-material-apply-list
            :data="scope.row[materialField.fieldName]"
            :columns="materialSubFields"
          />
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
      <!-- end 展开行 -->

      <el-table-column
        v-for="column in columns"
        :key="column.fieldName"
        :label="column.displayName"
        :prop="column.fieldName"
        show-overflow-tooltip
        :min-width="column.minWidth || '88px'">
        <template slot-scope="scope">
          <template v-if="column.fieldName === 'serialNumber'" >
            <a href="javascript:void(0)" class="view-detail-btn task-list-numbering" @click="showProcessDetail(scope.row)">
              {{ $formatFormField(column, scope.row) }}
            </a>
          </template>
          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部数据量统计 -->
    <div class="table-footer">
      <i18n path="common.base.table.totalCount">
        <span place="count" class="level-padding">{{data.length || 0}}</span>
      </i18n>
    </div>

    <task-material-apply-dialog
      ref="TaskMaterialApplyDialog"
      :app-id="appId"
      :form-id="templateId"
      :form-content-id="formContentId"
      :processor-instance-id="processorInstanceId"
      :is-detail="iFrameIsDetail"
      :task="task"
      @success="getMaterialList"
    />
  </div>
</template>

<script>
/* api */
import * as PassApi from '@src/api/PassApi';
/* components */
import TaskMaterialApplyList from './TaskMaterialApplyList.vue';
import TaskMaterialApplyDialog from './TaskMaterialApplyDialog.vue';

export default {
  name: 'task-material-list',
  props: {
    task: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      loading: true,
      data: [], // 列表数据
      fields: [], // 表单字段
      appId: '7f042692-0581-4370-bdb0-ce97ca2c3a2a', // 应用id
      templateId: 'c16752ef-b018-47cf-94d6-ddb7ab509b4e', // 表单id,
      formContentId: '',
      processorInstanceId: '',
      iFrameIsDetail: false
    }
  },
  computed: {
    // 显示展开行
    showExpand() {
      let { id, fieldName } = this.materialField || {};
      return id && this.data.some(item => item[fieldName] && item[fieldName].length);
    },
    /* 物料字段 */
    materialField() {
      return this.fields.find(field => field.formType == 'materialOrder') || {};
    },
    /* 物料子字段 */
    materialSubFields() {
      return this.materialField?.subFormFieldList || [];
    },
    /* 关联工单字段 */
    relatedTaskField() {
      return this.fields.find(field => field.formType == 'related_task') || {};
    },
    /* 编号字段 */
    serialNumberField() {
      return this.fields.find(field => field.formType == 'serialNumber') || {};
    },
    /* 列 */
    columns() {
      let { displayName = this.$t('common.form.preview.sparepart.colum18') } = this.serialNumberField;

      return [
        {
          displayName,
          fieldName: 'serialNumber',
          formType: 'serialNumber',
          minWidth: '120px'
        },
        {
          displayName: this.$t('common.base.createUser'),
          fieldName: 'createUser',
          formType: 'user'
        },
        {
          displayName: this.$t('common.base.dataState'),
          fieldName: 'customStatus',
          formType: 'select'
        },
        {
          displayName: this.$t('common.base.createTime'),
          fieldName: 'createTime',
          formType: 'datetime',
          minWidth: '120px'
        }
      ];
    }
  },
  mounted() {
    this.fetchFields();
  },
  methods: {
    showProcessDetail(record) {
      const { bizId, processorInstanceId } = record
      this.formContentId = bizId
      this.processorInstanceId = processorInstanceId
      this.iFrameIsDetail = true

      this.$refs.TaskMaterialApplyDialog.open(this.$t('task.detail.components.materialApprove'))
    },
    getRowClass(item) {
      let { fieldName } = this.materialField || {};

      // 无物料子表单数据时隐藏展开行按钮
      if (!fieldName || !item.row[fieldName] || !item.row[fieldName].length) {
        return 'base-table-row-v3 row-expand-cover';
      }

      return 'base-table-row-v3';
    },
    /* 查询物料清单列表数据 */
    getMaterialList() {
      const params = {
        templateBizId: this.templateId,
        pageNum: 1,
        pageSize: -1, // 不分页
        conditions: [{
          key: 'taskNo',
          operator: 'array_eq',
          value: this.task.taskNo,
          property: this.relatedTaskField.fieldName
        }]
      }

      this.loading = true;

      PassApi.searchList(params)
        .then(res => {
          const { success, data } = res;
          if (!success || !data) return;

          // 处理数据
          data.list = (data?.list || []).map(item => {
            return { ...item, ...item.formValue, customStatus: this.fromatStatus(item.customStatus, item.esTaskList) };
          });
          this.data = data.list || [];
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
          console.error('err', err);
        });
    },
    /**
     * 描述 判断是否有回退节点（设置已拒绝）
     * @date 2022-05-16
     * @param {any} customStatus 原始自定义数据状态
     * @param {any} esTaskList 所有节点任务状态
     * @returns {any}
     */
    fromatStatus(customStatus, esTaskList){
      const rejectTaskList = esTaskList.filter(item=> item.status === 2)

      if(rejectTaskList.length > 0) {
        const sortRejectTaskList = rejectTaskList.sort((prev, next) => prev.finishedTime - next.finishedTime)
        if([4, 7].includes(sortRejectTaskList[sortRejectTaskList.length - 1].approveResult)) return [this.$t('common.task.type.refused')]
      }
      
      return customStatus
    },
    /* 查询表单字段 */
    fetchFields() {
      return PassApi.getFormFieldListInfo({ templateBizId: this.templateId })
        .then(res => {
          let { paasFormFieldVOList = [] } = res?.data || {};
          this.fields = paasFormFieldVOList;

          this.getMaterialList();
        })
        .catch(err => console.error('err', err));
    },
    openApplyDialog() {
      this.iFrameIsDetail = false
      this.$refs.TaskMaterialApplyDialog.open(this.$t('task.detail.components.addMaterialList'));
    }
  },
  components: {
    [TaskMaterialApplyList.name]: TaskMaterialApplyList,
    [TaskMaterialApplyDialog.name]: TaskMaterialApplyDialog
  }
}
</script>

<style lang="scss">
.task-material-list {
  padding: 16px;
  .mb-12 {
    margin-bottom: 12px;
  }
  .task-material-table {
    border-top: 1px solid #ebeef5;

    .el-table__empty-block {
      border-bottom: 1px solid #ebeef5;
    }

    .el-table__expand-icon  {
      height: 100%;
      top: -2px;
      left: 12px;

      .el-icon {
        font-size: $font-size-base;
        font-weight: bold;
      }
    }

    .row-expand-cover {
      .el-table__expand-icon  {
        display: none;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
::v-deep .el-table__expanded-cell {
  padding: 0 0 0 40px;
  background: $bg-color-l1;

  &:hover {
    background: $bg-color-l1 !important;
  }
}
</style>
